﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace StandaloneSilverlightWoZ.Web
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    //[WebService(Namespace = "http://tempuri.org/")]
    //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CollectedDataFileReciever : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // if the query string changes here, change it in SilverlightWoZApplication also
            string filename = context.Request.QueryString["filename"].ToString();
            //using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
            using (StreamWriter fs = new StreamWriter(context.Server.MapPath("~/App_Data/" + filename)))
            {
                File.SetAttributes(context.Server.MapPath("~/App_Data/" + filename), FileAttributes.Normal);
                SaveFile(context.Request.InputStream, fs);
            }
        }

        private void SaveFile(Stream stream, StreamWriter fs)
        {
            StreamReader sr = new StreamReader(stream);
            StreamWriter sw = fs;//new StreamWriter(fs);
            string result=sr.ReadToEnd();
            sw.Write(result);
            sw.Flush();
            sw.Close();
            #region Another way
            //char[] buffer = new char[4096];
            //while (!sr.EndOfStream)
            //{
            //    sr.Read(buffer,0,buffer.Length);
            //    sw.Write(buffer);
            //}
            //sr.Close();
            //sw.Flush();
            //sw.Close();
            //byte[] buffer = new byte[4096];
            //int bytesRead;
            #endregion

            #region Yet another way
            //while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            //{
            //    fs.Write(buffer, 0, bytesRead);
            //}
            //fs.Flush(); fs.Close();
            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
